const model = require('../models/bannerModel'),
  cronModel = require('../models/cronModel'),
  errCode = require('../../conf/errorCode'),
  wrap = require('../helper/wrap'),
  conf = require('../../conf/const'),
  util = require('../helper/util'),
  moment = require('moment'),
  _ = require('lodash'),
  {parseIntPageSize} = require('./commonService');

const DATE_FORMAT = 'YYYY-MM-DD HH:mm';

//根据type不同，做changeData的区分
var wrapDataFunc = function(type, operateObj) {
  let wrapName = '';
  switch (type) {
    case 'banner':
      wrapName = wrap.names.banner;
      break;
    case 'news':
      wrapName = wrap.names.news;
      break;
    case 'comment':
      wrapName = wrap.names.comment;
      break;
    case 'topic':
      wrapName = wrap.names.topic;
      break;
    case 'subject':
      wrapName = wrap.names.subject;
      break;
    default:
      wrapName = wrap.names.data;
      break;
  }
  return wrap.changeData(
    operateObj,
    wrapName,
    wrap.names.front,
    wrap.names.end,
  );
};

exports.addData = function(
  //{type, title, subtitle, img, validateDate, releateArticle},
  {type, ...operateObj},
  callback,
) {
  //var tmp = util.firstKeyOfNull(
  //{type, title, subtitle, img, validateDate, releateArticle},
  //['type', 'title', 'subtitle', 'img', 'validateDate', 'releateArticle'],
  //);
  //if (tmp != null) {
  //return callback({errNo: errCode.LESS_OF_DATA_ERROR, extraMsgs: tmp});
  //}
  model.add(type, wrapDataFunc(type, operateObj), (err, result) => {
    if (err) return callback(err);
    return callback(null, {id: result.insertId});
  });
};

var getOperateByPage = (exports.getOperateByPage = async function(
  type,
  flag,
  page,
  size,
  callback,
) {
  let errMsgs = null;
  [errMsgs, page, size] = parseIntPageSize(page, size);
  if (errMsgs == null) {
    //更新数据
    let updateRel = await cronModel.updateAllOperateDataStatus(type);

    model.getOperateByPage(type, flag, page, size, (err, _rel) => {
      if (err) {
        return callback(err);
      }

      let index = 0;
      _rel.list.map(item => {
        item.validateDate = moment(item.validateDate).format(DATE_FORMAT);
        item.index = index++;
      });

      if (flag == 0 || _rel.list.length <= 0) {
        //已过期或者没有数据
        return callback(null, _rel);
      }

      //排序问题
      let head = _rel.list.filter(item => {
          return item.prevId == -1;
        })[0],
        rel = [];

      rel.push(head);
      while (head.nextId != -1) {
        let p = _rel.list.filter(item => {
          return head.nextId == item.id;
        });
        head = [].concat(p)[0];
        rel.push(head);
      }

      _rel.list = rel;
      return callback(null, _rel);
    });
  } else callback({errNo: errCode.INVALID_PARAM_ERROR, extraMsgs: errMsgs});
});

exports.deleteOperateByIds = function(type, ids, callback) {
  if (_.isString(ids)) {
    ids = ids.trim().split(',');
    if (
      !_.every(ids, function(value) {
        return util.isIntegerLike(value);
      })
    ) {
      return callback({errNo: errCode.INVALID_FORMAT_ERROR, extraMsgs: 'ids'});
    }
  } else if (_.isNumber(ids)) {
    ids = [ids];
  } else if (
    !_.isArray(ids) ||
    !_.every(ids, function(value) {
      return util.isIntegerLike(value);
    })
  ) {
    return callback({errNo: errCode.INVALID_FORMAT_ERROR});
  }
  if (ids.length == 0) {
    return callback(null, {deleted: 0});
  }

  model.deleteOperateByIds(type, ids, (err, result) => {
    if (err) return callback(err);
    return callback(null, {
      deleted: result.changedRows,
    });
  });
};

exports.updateData = function(type, operateId, data, callback) {
  //var tmp = util.findInvalidKeyBy(data, {
  //orders: v => {
  //return util.isIntegerLike(v) && 0 <= ~~v && ~~v <= 20;
  //},
  //});
  //if (tmp != null) {
  //return callback({errNo: errCode.INVALID_PARAM_ERROR, extraMsgs: tmp});
  //}

  return model.updateData(
    type,
    operateId,
    wrap.changeData(data, wrap.names[type], wrap.names.front, wrap.names.end),
    (err, result) => {
      if (err) return callback(err);
      return callback(null, {
        affectData: result.affectedRows,
        updatedData: result.changedRows,
      });
    },
  );
};

exports.moveOperatePosition = function(type, operateId, moveType, callback) {
  return model.moveOperatePosition(type, operateId, moveType, callback);
};
